import React, { Component } from 'react';
import { Button, Icon ,List, InputItem, WhiteSpace,Checkbox} from 'antd-mobile';
// import { createForm } from 'rc-form';
import styles from './pay.css';

import fetchUtil from "../utils/fetchUtil";

import Pay from '../utils/wxpay';
import { getUserInfo, getEquipDetail, getUserToken,tradeAdd,dealEquip,getEquipState } from './actions';

const CheckboxItem = Checkbox.CheckboxItem;

const CheckButton = ({money,checked,onClick}) => {
    return <div 
    onClick={onClick}
    className={checked?styles.buttonPressed:styles.buttonNormal}>
        {money}元
    </div>
}

class App extends Component {

    constructor() {
        super();
        this.state = {
            equipId:0,
            equipNo:'',
            equipImg:'',
            inputValue:6,
            ischeck:false,
            payvalue:6,
            walletValue:0,
            equipStateString:'',
            equipState:0,//0：不可用，1：可用
        }
    }

    onChange = (value) => {
        console.log(value);
        this.setState({ischeck:!value})

        let walletValue = this.state.walletValue;
        let inputValue = this.state.inputValue;

        if (!value){
            if (walletValue > inputValue){
                this.setState({payvalue:0});
            }else{
                this.setState({payvalue:(parseFloat(inputValue)-parseFloat(walletValue)).toFixed(2)});
            }
        }else{
            this.setState({payvalue:inputValue});
        }
    }

    componentDidMount(){
        let equipNo = this.props.match.params.equipNo;

        getEquipDetail(equipNo).then((data) => {
            this.setState({equipNo:data.equipNo,equipId:data.id,equipImg:data.img});
        })

        this.getEquipState(equipNo);

        getUserToken((token) => {
            getUserInfo(token).then((data) => {
                    this.setState({walletValue:(data.wallet/100)})
            })
       });
        
    }

    pay = () => {

        if (this.state.equipState == 0){
            alert(this.state.equipStateString);
            return;
        }

        let token = localStorage.getItem('token');

        let amount = parseFloat(this.state.payvalue).toFixed(2) * 100;

        let walletUsed = (parseFloat(this.state.inputValue)-parseFloat(this.state.payvalue)).toFixed(2) * 100;


        let params= {
            token:token,
            equipNo:this.state.equipNo,
            amount:amount,
            walletUsed:walletUsed,
        }

        tradeAdd(params).then((data) => {
            if (data.id != undefined){
                let id = data.id;
                console.log(data);
                if (data.amount == 0){
                    this.dealEquip(id);
                }else{
                    this.gotoPay(id);
                }
            }
        })
    }

    gotoPay = (id) => {
        let token = localStorage.getItem('token');
        let openid = localStorage.getItem('openid');
        let params = {
            openId:openid,
            tradeId:id,
            token:token,
        }
        const self = this;
        fetchUtil.commonRequest('http://node.7chejian.com/api/trade/pay',params).then((data) => {
            window.WeixinJSBridge.invoke(
                'getBrandWCPayRequest', {
                    "appId":data.appId,     //公众号名称，由商户传入     
                    "timeStamp":data.timeStamp,         //时间戳，自1970年以来的秒数     
                    "nonceStr":data.nonceStr, //随机串     
                    "package":data.package,     
                    "signType":data.signType,         //微信签名方式：     
                    "paySign":data.paySign //微信签名 
                },
                function(res){    
                    if(res.err_msg == "get_brand_wcpay_request:ok" ) {
                        self.dealEquip(id);
                    }     // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。 
                }
            ); 

        })
    }

    dealEquip = (id) => {
        dealEquip(id).then((data) => {
            this.gotoPaySuccess();
        }).catch((error) => {
            
        })
    }


    getEquipState = (equipNo) => {
        getEquipState(equipNo).then((data) => {
            this.setState({equipStateString:'可使用',equipState:1})
        }).catch((data) => {
            this.setState({equipStateString:data.msg,equipState:0})
        })
    }

    gotoPaySuccess = () => {
        this.props.history.push('/success');
    }

    onClickMoney = (value) => {
        this.setState({
            inputValue:value,
            ischeck:false,
            payvalue:value,
        })
    }

    render() {
      return (
        <div className={styles.container}>
            <div className={styles.equipImg} >
                <img src={this.state.equipImg}
                 style={{width:'120px',height:'120px'}} />
            </div>
            <div className={styles.equipDiv}>
                设备号：{this.state.equipNo}
            </div> 

            <div className={styles.equipState}>
                ({this.state.equipStateString})
            </div> 

            <div className={styles.equipInputDiv}>
                <div className={styles.input}>
                {this.state.inputValue}
                </div>
                 元
            </div>

            <div className={styles.buttonC}>
                <CheckButton onClick={() => {this.onClickMoney(6)}} money={6} checked={this.state.inputValue == 6} />
                <CheckButton onClick={() => {this.onClickMoney(12)}} money={12}  checked={this.state.inputValue == 12}/>
                <CheckButton onClick={() => {this.onClickMoney(18)}} money={18}  checked={this.state.inputValue == 18}/>
            </div>

            <div className={styles.userwallet}>
                <CheckboxItem checked={this.state.ischeck} style={{paddingLeft: 0,}} onChange={() => this.onChange(this.state.ischeck)}>
                    是否使用余额(可用余额￥{this.state.walletValue})
                </CheckboxItem>
            </div>
            
            <Button onClick={() => {this.pay()}}  style={{marginBottom:'10px'}} type="primary">支付  {this.state.payvalue}  元</Button>
        </div>
      );
    }
  }
  
  export default App;